import asyncio
import functools
import importlib
from nicegui import ui
import sys
import os


sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

nav_bar_entrys = []
list_of_tabs = ["tasks", "task_detail", "file"]


def nav_bar_wrapper(func):

    def common_func():
        with ui.row().classes("w-full"):
            for entry in nav_bar_entrys:
                if entry["title"] is None:
                    continue
                ui.link(entry["title"], target=entry["url"])
            ui.space()

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        common_func()
        return func(*args, **kwargs)

    @functools.wraps(func)
    async def wrapper_async(*args, **kwargs):
        common_func()
        return await func(*args, **kwargs)

    if asyncio.iscoroutinefunction(func):
        return wrapper_async
    return wrapper


for tab in list_of_tabs:
    mod = importlib.import_module(
        f"rr.ui.tabs.{tab}",
    )
    page_config = mod.page_config
    for entry in page_config["nav_entry"]:
        # logger.info(entry)
        nav_bar_entrys.append(entry)
        ui.page(entry["url"])(nav_bar_wrapper(entry["function"]))


@ui.page("/")
@nav_bar_wrapper
def ui_main():
    ui.navigate.to("/tasks")


# loading apis
# list_of_apis = ["storage_server", "task_output", "tasks"]
# for api in list_of_apis:
#     mod = importlib.import_module(f"runner.api.{api}")


def main():
    storage_secret = (
        "your_storage_secret_here"  # Replace with your actual storage secret
    )
    ui.run(storage_secret=storage_secret, show=False, dark=False, root_path="/rr_ui")


if __name__ in {"__main__", "__mp_main__"}:
    main()
